﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using CloseableTabItemDemo;
using swaganomics.Backend;
using swaganomics.Metro.Native;
using System.Web.Script.Serialization;
using System.Windows.Threading;

namespace swaganomics.Windows
{
    /// <summary>
    /// Interaction logic for HomeWindow.xaml
    /// </summary>
    public partial class HomeWindow : Window
    {
        public Backend.DataFormats.ServerResponse.Response TaxData;

        private bool inputData = true;
        private DispatcherTimer inputDataTimer = new DispatcherTimer();

        public HomeWindow()
        {
            InitializeComponent();
            DwmDropShadow.DropShadowToWindow(this);
            this.AddHandler(CloseableTabItem.CloseTabEvent, new RoutedEventHandler(this.CloseTab));
            Settings.homeWindow = this;
            Window_StateChanged(null, null);
            OpacityMask.Visibility = System.Windows.Visibility.Collapsed;

            inputDataTimer.Interval = new TimeSpan(0, 0, 2);
            inputDataTimer.Tick += inputDataTimer_Tick;
            inputDataTimer.Start();

            //JavaScriptSerializer jss = new JavaScriptSerializer();
            //Backend.DataFormats.ServerInput.Input input = new Backend.DataFormats.ServerInput.Input()
            //{
            //    Action = "calculate",
            //    Content = new Backend.DataFormats.ServerInput.Content()
            //    {
            //        Age = 25,
            //        Gender = 0,
            //        YearlyIncome = 56000
            //    }
            //};

            //string json = jss.Serialize(input);
            //Backend.DataFormats.ServerResponse.Response responce = jss.Deserialize<Backend.DataFormats.ServerResponse.Response>(ServerConnector.GetServerResponse(json));
        }
        void inputDataTimer_Tick(object sender, EventArgs e)
        {
            if (inputData)
            {
                OpacityMask.Visibility = System.Windows.Visibility.Visible;
                inputData = false;
                Metro.Dialogs.EnterData enterData = new Metro.Dialogs.EnterData(this.Width);
                enterData.Owner = this;
                enterData.ShowDialog();

                OpacityMask.Visibility = System.Windows.Visibility.Collapsed; ;
            }
        }

        protected override void OnSourceInitialized(EventArgs e)
        {
            base.OnSourceInitialized(e);

            System.IntPtr handle = (new System.Windows.Interop.WindowInteropHelper(this)).Handle;
            System.Windows.Interop.HwndSource.FromHwnd(handle).AddHook(new System.Windows.Interop.HwndSourceHook(WindowProc));
        }
        private void CloseTab(object source, RoutedEventArgs args)
        {
            TabItem tabItem = args.Source as TabItem;
            if (tabItem != null)
            {
                dynamic tabContent = tabItem.Content;

                if (tabContent.Close())
                {
                    TabControl tabControl = tabItem.Parent as TabControl;
                    if (tabControl != null)
                        tabControl.Items.Remove(tabItem);
                }
            }
        }
        private void homeTabControl_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            TabItem tab = (TabItem)homeTabControl.SelectedItem;

            if (tab != null)
                UpdateTitleText(tab.Header.ToString().Replace("__", "_").Replace(".map", ""));

            //if (tab != null && tab.Header.ToString() == "Start Page")
            //    ((StartPage)tab.Content).UpdateRecents();
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="update"></param>
        public void UpdateTitleText(string update)
        {
            lblTitle.Text = string.Format("{0} - {1}", update, "Swaganomics");
        }

        #region More WPF Annoyance
        private void headerThumb_DragDelta(object sender, DragDeltaEventArgs e)
        {
            Left = Left + e.HorizontalChange;
            Top = Top + e.VerticalChange;
        }

        private void ResizeDrop_DragDelta(object sender, DragDeltaEventArgs e)
        {
            double yadjust = this.Height + e.VerticalChange;
            double xadjust = this.Width + e.HorizontalChange;

            if (xadjust > this.MinWidth)
                this.Width = xadjust;
            if (yadjust > this.MinHeight)
                this.Height = yadjust;
        }
        private void ResizeRight_DragDelta(object sender, DragDeltaEventArgs e)
        {
            double xadjust = this.Width + e.HorizontalChange;

            if (xadjust > this.MinWidth)
                this.Width = xadjust;
        }
        private void ResizeBottom_DragDelta(object sender, DragDeltaEventArgs e)
        {
            double yadjust = this.Height + e.VerticalChange;

            if (yadjust > this.MinHeight)
                this.Height = yadjust;
        }

        private void Window_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Normal)
            {
                btnActionMaxamize.Visibility = System.Windows.Visibility.Visible;
                btnActionRestore.Visibility = System.Windows.Visibility.Collapsed;
            }
            else if (this.WindowState == System.Windows.WindowState.Maximized)
            {
                btnActionMaxamize.Visibility = System.Windows.Visibility.Collapsed;
                btnActionRestore.Visibility = System.Windows.Visibility.Visible;
            }
        }
        private void headerThumb_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.WindowState == System.Windows.WindowState.Normal)
                this.WindowState = System.Windows.WindowState.Maximized;
            else if (this.WindowState == System.Windows.WindowState.Maximized)
                this.WindowState = System.Windows.WindowState.Normal;
        }
        private void btnActionMinimize_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Minimized;
        }
        private void btnActionRestore_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Normal;
        }
        private void btnActionMaxamize_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            this.WindowState = System.Windows.WindowState.Maximized;
        }
        private void btnActionClose_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Application.Current.Shutdown();
        }

        #region Maximize Workspace Workarounds
        private System.IntPtr WindowProc(
              System.IntPtr hwnd,
              int msg,
              System.IntPtr wParam,
              System.IntPtr lParam,
              ref bool handled)
        {
            switch (msg)
            {
                case 0x0024:
                    WmGetMinMaxInfo(hwnd, lParam);
                    handled = true;
                    break;
            }

            return (System.IntPtr)0;
        }
        private void WmGetMinMaxInfo(System.IntPtr hwnd, System.IntPtr lParam)
        {
            swaganomics.Metro.Native.Monitor_Workarea.MINMAXINFO mmi = (swaganomics.Metro.Native.Monitor_Workarea.MINMAXINFO)Marshal.PtrToStructure(lParam, typeof(swaganomics.Metro.Native.Monitor_Workarea.MINMAXINFO));

            // Adjust the maximized size and position to fit the work area of the correct monitor
            int MONITOR_DEFAULTTONEAREST = 0x00000002;
            System.IntPtr monitor = swaganomics.Metro.Native.Monitor_Workarea.MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);

            if (monitor != System.IntPtr.Zero)
            {
                //System.Windows.Forms.Screen scrn = System.Windows.Forms.Screen.FromHandle(new WindowInteropHelper(this).Handle);

                swaganomics.Metro.Native.Monitor_Workarea.MONITORINFO monitorInfo = new swaganomics.Metro.Native.Monitor_Workarea.MONITORINFO();
                swaganomics.Metro.Native.Monitor_Workarea.GetMonitorInfo(monitor, monitorInfo);
                swaganomics.Metro.Native.Monitor_Workarea.RECT rcWorkArea = monitorInfo.rcWork;
                swaganomics.Metro.Native.Monitor_Workarea.RECT rcMonitorArea = monitorInfo.rcMonitor;
                mmi.ptMaxPosition.x = Math.Abs(rcWorkArea.left - rcMonitorArea.left);
                mmi.ptMaxPosition.y = Math.Abs(rcWorkArea.top - rcMonitorArea.top);
                mmi.ptMaxSize.x = Math.Abs(rcWorkArea.right - rcWorkArea.left);
                mmi.ptMaxSize.y = Math.Abs(rcWorkArea.bottom - rcWorkArea.top);

                /*
                mmi.ptMaxPosition.x = Math.Abs(scrn.Bounds.Left - scrn.WorkingArea.Left);
                mmi.ptMaxPosition.y = Math.Abs(scrn.Bounds.Top - scrn.WorkingArea.Top);
                mmi.ptMaxSize.x = Math.Abs(scrn.Bounds.Right - scrn.WorkingArea.Left);
                mmi.ptMaxSize.y = Math.Abs(scrn.Bounds.Bottom - scrn.WorkingArea.Top);
                */
            }

            Marshal.StructureToPtr(mmi, lParam, true);
        }
        #endregion
        #endregion
    }
}